<?php
/**
 * Created by PhpStorm.
 * User: 董伟
 * Date: 2019/9/11
 * Time: 9:08
 */

namespace app\api\controller\v1;
use app\common\model\Members;
use app\common\service\ShopType;
use app\facade\ShopType as ShopTypeFacade;
use app\facade\Stores as StoresFacade;
use app\common\model\Stores as StoresModel;
use app\facade\GoodsCollect;
use app\facade\NewOrder as NewOrderFacade;
use app\common\model\MemberYongjin;
use app\facade\Orders as OrdersFacade;

class Stores extends Base
{
    /*
     * 行业分类---全部
     * */
    public function shop_type(){
        $list=ShopTypeFacade::all_cate();
        return j(0,'获取成功',$list);
    }

    /*子类*/
    public function sub_cate(){
        $parent_id=input('parent_id',0);
        $list=ShopTypeFacade::sub_cate($parent_id);
        return j(0,'获取成功',$list);
    }


    /*
     * 注册商家
     * @author 董伟
     * */
    public function reg_shop(){
        $userId = $this->checkUserToken();
        $data=input('post.');
        if(!isset($data['id'])){
            $info=StoresModel::field(true)->where('uid',$userId)->find();
            if($info){
                return j(1, '您已经注册过了');
            }
        }

        if(!isset($data['address'])){
            return j(1, '地址不存在');
        }

        if(!isset($data['type_id'])){
            return j(1, '分类不存在');
        }

        if(!isset($data['name'])){
            return j(1, '商户名称不能为空');
        }

        if(!isset($data['contact_name'])){
            return j(1, '联系人不能为空');
        }

        if(!isset($data['pic'])){
            return j(1, '营业执照不能为空');
        }
        $data['userid']=$userId;
        $ret=StoresFacade::add($data);
        return j(0, '成功',$ret);
    }

    /*
     * 商户列表
     * @author 董伟
     * */

    public function shop_list(){
//        $userId = $this->checkUserToken();
        $province=input('province/d',0);
        $city=input('city/d',0);
        $page       = input('post.page/d', 1);
        $limit      = input('post.limit/d', 10);
        // 分页偏移量
        $offset     = ($page - 1) * $limit;
        $limit      = $offset.','.$limit;

        $type_id=input('type_id/d',0);//二类
        $category_id=input('category_id/d',0);//大类
        $lng = input('lng', '125.333139');
        $lat = input('lat', '43.952791');
        $distance=input('distance',0);
        $salecount=input('salecount',0);
        $title=input('title','');

        $order='is_flag desc,distance asc,id desc';
        $where[]=[
            ['status', 'eq', 1],
            ['province','eq',$province],
            ['city','eq',$city],
            ['is_perfect','eq',1],
            ['delete_time','eq',0]
        ];
        if($title){
            $where[]    = [
                ['name', 'like', '%'.$title.'%'],
            ];
        }

        $where_rt_a=[];
        $where_rt_b=[];
        if($category_id){
            $where_rt_a ="find_in_set($category_id,category_id)";
        }
        if($type_id){
            $where_rt_b ="find_in_set($type_id,type_id)";
        }

        $all=array(
            'lat'=>$lat,
            'lng'=>$lng,
            'where_rt_a'=>$where_rt_a,
            'where_rt_b'=>$where_rt_b,
        );
        if($distance){
            $order='distance asc';
        }
        if($salecount){
            $order='salecount desc';
        }



        $shop_list=StoresFacade::Stores($where,$limit,$order,'',$all);

        $tj_list=StoresModel::field("id,image_uri,name,content,photos")->where('is_flag',1)->where('is_perfect',1)->where('delete_time',0)->append(['image_uri','photos'])->order('id desc')->select();
        $list=array();
        foreach($shop_list as $k=>$v){
            $shop_list[$k]['distance']=$v['distance'].'Km';
        };

        $data=array(
            'shop_list'=>$shop_list,
            'tj_list'=>$tj_list
        );


        return j(0, '成功',$data);

    }

    /*
     * 商户的详情
     * @author 董伟
     * */
    public function shop_detail(){
        $userId = $this->checkUserToken();
        $id=input('id/d',0);
        $lng = input('lng', '125.333139');
        $lat = input('lat', '43.952791');
        if(!$id){
            return j(1,'参数不正确');
        }
        $all=array(
            'lat'=>$lat,
            'lng'=>$lng
        );
        $info=StoresFacade::detail($id,'','',$all);

        //门店分类组装数组

        $info['type_list']=StoresFacade::getTypeList($info['category_id'],$info['type_id']);

        // $info['distance']=number_format($info['distance'],2);
        $where = [
            'userid'   => $userId,
            'goods_id' => $id,
            'type'=>1
        ];
        $info['is_collect'] = GoodsCollect::isCollect($where,1);
        return j(0,'成功',$info);

    }

    //核销订单
    public function verification(){
        $userId = $this->checkUserToken();
        $verification_code     = input('verification_code', 0);
        try {
            $result = OrderGoods::field(true)->where('verification_code',$verification_code)->find();
            if ($result) {
                $result->verification_status = 1;
                $result->save();
                return j(0, '确认核销成功');
            }
            return j(1, '核销失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

    /*
     * 获取省市区
     * */
    public function region(){
        $list=StoresFacade::linkage();
        return j(0,'获取成功',$list);
    }

    /*判断是否注册过商户*/
    public function shop_condition(){
        $userId = $this->checkUserToken();
        $info=StoresModel::field(true)->where('uid',$userId)->find();
        if(!$info){
            $data['status']=3;
            $data['id']=0;
        }else{
            $data['status']=$info['status'];
            $data['id']=$info['id'];//0申请中，1是审核成功，2是审核拒绝，3是未申请
            $data['remark']=$info['remark'];//理由
        }
        return j(0,'获取成功',$data);
    }


    /*完善商家信息*/
    public function shop_update(){
        $userId = $this->checkUserToken();
        $post=input('post.');
        //file_put_contents('1.txt',json_encode($post));
        $temp = [
            // 'category_id'=>$post['category_id'],
            //'type_id' => isset($post['type_id'])?$post['type_id']:'',
            'name' => $post['name'],
            'contact_name'=>isset($post['contact_name'])?$post['contact_name']:'',
            'idcard_txt'=>isset($post['idcard_txt'])?$post['idcard_txt']:'',
            'idcard_id'=>isset($post['idcard_id'])?$post['idcard_id']:'',
            'pic'=>isset($post['pic'])?$post['pic']:'',
            'province' => isset($post['province'])?$post['province']:'',
            'city' => isset($post['city'])?$post['city']:'',
            'district'=>isset($post['district'])?$post['district']:'',
            'address'=>isset($post['address_txt'])?$post['address_txt']:'',
            'address_txt'=>isset($post['address_txt'])?$post['address_txt']:'',
            'lng'=>isset($post['lng'])?$post['lng']:'',
            'lat'=>isset($post['lat'])?$post['lat']:'',
            'startdt'=>isset($post['startdt'])?$post['startdt']:'',
            'enddt'=>isset($post['enddt'])?$post['enddt']:'',
            'image_uri'=>isset($post['image_uri'])?$post['image_uri']:'',
            'phone'=>isset($post['phone'])?$post['phone']:'',
            'photos'=>isset($post['photos'])?$post['photos']:'',
            'hj_pic'=>isset($post['hj_pic'])?$post['hj_pic']:'',
            'content'=>isset($post['content'])?$post['content']:'',
            'discount'=>isset($post['discount'])?$post['discount']:'',
            'zhuying'=>isset($post['zhuying'])?$post['zhuying']:'',
            'is_perfect'=>1,
           // 'category_id'=>isset($post['category_id'])?$post['category_id']:'',
            //'type_id'=>isset($post['type_id'])?$post['type_id']:''
        ];

        StoresModel::field(true)->where('uid',$userId)->update($temp);
        return j(0,'获取成功');
    }

    /*商户的订单*/
    public function shop_orderlist(){
        $userId = $this->checkUserToken();
        $isShipping = input('post.is_shipping/d', 0);
        $tabIndex   = input('post.tabIndex/d', 0);
        $shopInfo=StoresModel::field(true)->where('uid',$userId)->find();
        if(!$shopInfo){
            return j(1,'商家不存在');
        }
        $page       = input('post.page/d', 1);
        $limit      = input('post.limit/d', 10);
        // 分页偏移量
        $offset     = ($page - 1) * $limit;
        $limit      = $offset.','.$limit;
        $list=OrdersFacade::shop_orderList($shopInfo['id'], $limit, $tabIndex, $isShipping);
        return j(0, '成功', $list);
    }

    /*
    * 商家余额变动-----不要了
    * @author 董伟
    * */
    public function balanceRecords()
    {
        $userId = $this->checkUserToken();
        $type = input('type', 0);
        $page = input('post.page/d', 1);
        $limit = input('post.limit/d', 10);
        // 分页偏移量
        $offset = ($page - 1) * $limit;
        $limit = $offset . ',' . $limit;

        $shopInfo=StoresModel::field('id,name,image_uri,category_id,balance')->where('uid',$userId)->append(['category_name','image_uri'])->find();
        if(!$shopInfo){
            return j(1, '商家不存在');
        }

        try {
            $result['list'] = StoresFacade::balance($shopInfo['id'], $limit,$type);
            $result['shopInfo'] = $shopInfo;
            return j(0, '获取数据成功', $result);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

    /*商家提现*/
    public function cash()
    {
        $userId = $this->checkUserToken();
        $post = input('post.');
        $info = StoresModel::field(true)->where(['uid' => $userId])->find();
        try {
            $result = StoresFacade::cash($info['id'], $post);
            if ($result) {
                return j(0, '申请提现成功');
            }
            return j(1, '申请提现失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    /**
     * 提现记录
     */
    public function cashRecord()
    {
        $userId = $this->checkUserToken();
        $page   = input('post.page/d', 1);
        $limit  = input('post.limit/d', 10);
        // 分页偏移量
        $offset = ($page - 1) * $limit;
        $limit  = $offset.','.$limit;

        $info = StoresModel::field(true)->where(['uid' => $userId])->find();
        try {

            $result = StoresFacade::cashRecord($info['id'],$limit);

            return j(0, '成功', $result);

        } catch (\Exception $e) {

            return j(1, $e->getMessage());

        }

    }


    /*
   * 生成二维码
   * @author 董伟
   */
    public function myQRcode()
    {
        try {
            $userId = $this->checkUserToken();
            //$userId=27;
            $info = StoresModel::field(true)->where(['uid' => $userId])->find();
            if (!$info) {
                return j(1, '商家不存在');
            }
            $arg=array(
                'id'=>$info['id'],
                'shop_name'=>$info['name']
            );



            $url = StoresFacade::generateQrCode($arg);

            $data = [
                'url' => $url
            ];
            return j(0, '生成二维码成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }

    /*搜索用户*/
    public function user_list(){
        $userId = $this->checkUserToken();
        $mobile=input('mobile','');
        $where=[
            ['mobile','like','%'.$mobile.'%'],
            ['id','neq',$userId],
        ];
        $list=Members::field('id,wechat_id,nickname')->where($where)->order('id desc')->select();
        return j(0, '成功', $list);
    }

    /*
     * 创建门店
     * */
    public function add_shop(){
        $userId = $this->checkUserToken();
        $data=input('post.');
        $info = StoresModel::field(true)->where(['uid' => $userId])->find();
        $data['shop_id']=$info['id'];//总店id
        if(!isset($data['address'])){
            return j(1, '地址不存在');
        }

        if(!isset($data['type_id'])){
            return j(1, '分类不存在');
        }

        if(!isset($data['name'])){
            return j(1, '商户名称不能为空');
        }

        if(!isset($data['contact_name'])){
            return j(1, '联系人不能为空');
        }

        if(!isset($data['pic'])){
            return j(1, '营业执照不能为空');
        }
        $data['userid']=$data['uid'];
        $ret=StoresFacade::add($data);
        if($ret){
            return j(0, '获取成功',$ret);
        }else{
            return j(1, '获取失败');
        }
    }

    /*
     * 商家其下的门店
     * 董伟
     * */
    public function stories_shop_list(){
        $userId = $this->checkUserToken();
        $info = StoresModel::field(true)->where(['uid' => $userId])->find();
        if(!$info){
            return j(1, '商家信息不存在');
        }
        $page   = input('post.page/d', 1);
        $limit  = input('post.limit/d', 10);
        // 分页偏移量
        $offset = ($page - 1) * $limit;
        $limit  = $offset.','.$limit;
        $list=StoresFacade::shop_list($info['id'],$limit);
        return j(0, '获取成功',$list);
    }

    /*
     * 删除门店
     * 董伟
     * */
    public function stories_del(){
        $userId = $this->checkUserToken();
        $id=input('id',0);//
        $info=StoresModel::field(true)->where('id',$id)->find();
        if(!$info){
            return j(1, '门店信息不存在');
        }
        $ret=StoresModel::field(true)->where('id',$id)->delete();
        if($ret){
            return j(0, '删除成功');
        }else{
            return j(1, '删除失败');
        }

    }

    /*
     * 门店的订单
     * 董伟
     * */
    public function z_orderlist(){
        $userId = $this->checkUserToken();
        $t_id=input('id',0);//子门的id
        $isShipping = input('post.is_shipping/d', 0);
        $tabIndex   = input('post.tabIndex/d', 0);
        $shopInfo=StoresModel::field(true)->where('uid',$userId)->find();
        if(!$shopInfo){
            return j(1,'商家不存在');
        }
        $page       = input('post.page/d', 1);
        $limit      = input('post.limit/d', 10);
        // 分页偏移量
        $offset     = ($page - 1) * $limit;
        $limit      = $offset.','.$limit;
        $list=OrdersFacade::shop_orderList($t_id, $limit, $tabIndex, $isShipping);
        return j(0, '成功', $list);
    }

    /*商户添加商品分类*/
    public function add_category(){
        $userId = $this->checkUserToken();
        $name=input('name/s','');
        $id=input('id/d',0);
        if(!$name){
            return j(1, '参数不正确');
        }
        $shopInfo=StoresModel::field(true)->where('uid',$userId)->find();
        if(!$shopInfo){
            return j(1, '商家不存在');
        }

        $arg=array(
            'store_id'=>$shopInfo['id'],
            'name'=>$name,
            'id'=>$id
        );
        $ret=StoresFacade::add_category($arg);
        return j(0, '成功');
    }

    /*商户余额*/
    public function my_yongjin()
    {
        $userId = $this->checkUserToken();
        $shopInfo=\app\common\model\Stores::field(true)->where('uid',$userId)->find();


        $data['tixian'] =$shopInfo['balance'];
        $data['list'] = MemberYongjin::field(true)->where('shop_id', $shopInfo['id'])->select()->toArray();

        return j(0, '获取信息成功', $data);
    }

    /*商户分类列表*/
    public function category_list(){
        $userId = $this->checkUserToken();
        $shopInfo=StoresModel::field(true)->where('uid',$userId)->find();
        if(!$shopInfo){
            return j(1, '商家不存在');
        }
        $data=StoresFacade::category_list($shopInfo['id']);
        return j(0, '成功',$data);

    }

    /*删除分类*/
    public function category_del(){
        $userId = $this->checkUserToken();
        $id=input('id/d',0);
        $data=$data=StoresFacade::category_del($id);
        return j(0, '成功',$data);
    }

    /*添加商品*/
    public function add_product(){
        $userId = $this->checkUserToken();
        $name=input('name/s','');
        $category_id=input('category_id/d',0);
        $sale_price=input('sale_price/s','');
        $goods_thumb_id=input('goods_thumb_id/d',0);
        $goods_intro=input('goods_intro/s','');
        $goods_album=input('goods_album/s','');
        $content_pic=input('content_pic/s','');
        $id=input('id/d',0);
        if(!$name){
            return j(1, '参数不正确');
        }

        if(!$category_id){
            return j(1, '分类id未选择');
        }



        $shopInfo=StoresModel::field(true)->where('uid',$userId)->find();
        if(!$shopInfo){
            return j(1, '商家不存在');
        }

        $arg=array(
            'store_id'=>$shopInfo['id'],
            'category_id'=>$category_id,
            'goods_name'=>$name,
            'sale_price'=>$sale_price,
            'goods_thumb_id'=>$goods_thumb_id,
            'id'=>$id,
            'goods_intro'=>$goods_intro,
            'goods_album'=>$goods_album,
            'content_pic'=>$content_pic
        );
        $ret=StoresFacade::add_product($arg);
        return j(0, '成功');
    }
    /*
     * 商品上下架
     * */
    public function product_sale(){
        $id=input('id/d',0);
        $sale_status=input('is_sale',0);
        $up=\app\common\model\Goods::where('id',$id)->update(['is_sale'=>$sale_status]);
        return j(0, '成功');
    }

    /*商户发布商品列表*/
    public function product_list(){
        $userId = $this->checkUserToken();
        $category_id=input('category_id/d',0);
        $shop_id=input('shop_id/d',0);
        if($shop_id){
            $shop_id=input('shop_id/d',0);
        }else{
            $shopInfo=StoresModel::field(true)->where('uid',$userId)->find();
            if(!$shopInfo){
                return j(1,'商家不存在');
            }
            $shop_id=$shopInfo['id'];
        }

        $page       = input('post.page/d', 1);
        $limit      = input('post.limit/d', 10);
        // 分页偏移量
        $offset     = ($page - 1) * $limit;
        $limit      = $offset.','.$limit;

        $list=StoresFacade::product_list($shop_id,$category_id, $limit);
        return j(0, '成功',$list);
    }

    /*产品删除*/
    public function product_del(){
        $userId = $this->checkUserToken();
        $id=input('id/d',0);
        $data=$data=StoresFacade::product_del($id);
        return j(0, '成功',$data);
    }

    /*商品详情*/
    public function product_detail(){
        $id=input('id/d',0);
        $info=StoresFacade::product_detail($id);
        return j(0, '成功',$info);
    }

    /**
     * 获取绑定银行卡信息
     */
    public function getBandData_shop(){
        $type = input('post.type',1);
        try{
            $userId = $this->checkUserToken();
            $shop_id=StoresModel::field(true)->where('uid',$userId)->value('id');

            $result = \app\facade\Stores::getBandData($shop_id,$type);

            return j(0, '成功', $result);
        }catch (\Exception $e){
            return j(1, $e->getMessage());
        }

    }





}